<?php
/**
 * 签名工具类
 *
 * @author dior <diaoxingkwan@vip.qq.com>
 *
 * @date 2021/06/01
 */

namespace app\common\util;


class Sign
{

    /**
     * 生成签名
     * @param string $timestamp 时间戳
     * @param string $nonceStr 随机字符串
     * @param string $appSecret app密钥
     * @return string
     */
    public static function makeSign(string $timestamp, string $nonceStr, string $appSecret): string
    {
        return sha1($appSecret . $nonceStr . $timestamp);
    }

    /**
     * 签名校验
     * @param array $params 请求参数
     * @param string $appSecret app密钥
     * @return bool|string
     */
    public static function verifySign(array $params, string $appSecret)
    {
        if (!isset($params['timestamp']) || !isset($params['nonceStr']) || !isset($params['sign'])) {
            return '参数缺失';
        }
        if (empty($appSecret)) {
            return '未配置密钥';
        }
        if (time() - intval($params['timestamp']) > 300) {
            return '签名已过期';
        }
        if (self::makeSign($params['timestamp'], $params['nonceStr'], $appSecret) !== $params['sign']) {
            return '签名验证失败';
        }
        return true;
    }

    /**
     * 生成请求URL
     * @param string $url 原URL
     * @param string $appSecret app密钥
     * @return string
     */
    public static function makeUrl(string $url, string $appSecret): string
    {
        //时间戳（秒级）
        $timestamp = (string)time();
        //随机字符串
        $nonceStr = Str::getRandomString(8);
        //构造URL
        $param = [
            'timestamp' => $timestamp,
            'nonceStr' => $nonceStr,
            'sign' => self::makeSign($timestamp, $nonceStr, $appSecret)
        ];
        return $url . '?' . http_build_query($param);
    }
}